<?php

class Common{
	public static function setPreviousURL($obj, $goBackFieldName)
	{
		$host = incGetHostUrl();
		$requestUri = $_SERVER['REQUEST_URI'];
		$fullURL = $host.$requestUri;
		$goBackField = "";
		
		if ($fullURL != $_SERVER['HTTP_REFERER'] && $fullURL != $_SERVER['HTTP_REFERER']."type/3/") {
			$goBackField = $_SESSION['GO_BACK_URL'] = $_SERVER['HTTP_REFERER'];
		}
		else {
			$goBackField = $_SESSION['GO_BACK_URL'];
		}
		
		if (isset($post[$goBackFieldName])) {
			$obj->set_property($goBackFieldName, $post[$goBackFieldName]);
		} else{
			$obj->set_property($goBackFieldName, $goBackField);
		}
	}	

    /**
     * Checks if given string is email address.
     *
     * @param string $var
     * @return bool
    */
    public static function var_is_email($var) {
    
    	$domain		= substr($var,strpos($var,"@")+1);
    	$mxhost		= array();
    	$count_dots	= sizeof(explode(".",$domain));
    
    	$not_an_email	= "(@.*@)|(\\.\\.)|(\\.@)|(@\\.)|(^\\.)";
    	$yes_an_email	= "^(([^><,;:\\[\\)\\(\\ ]+)|(\"[^\"]+\"))@(\\[?)[-_a-zA-Z0-9\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
    
    	if (eregi($not_an_email,$var) || !eregi($yes_an_email,$var)) {
    		$_ERR[]	= ERROR_EMAIL_BAD_SYNTAX;
    		return FALSE;
    	}
    
//    	if (USE_DNS_FUNCTIONS) {
//    		if (2 == $count_dots && !getmxrr($domain,$mxhosts)) { // domain.tld
//    			$_ERR[]	= ERROR_EMAIL_BAD_DOMAIN;
//    			return FALSE;
//    		}
//    	}
    
    	return $var;
    }
    
    /**
     * Checks if function is login
     *
     * @param string $var
     * @return bool
    */
    public static function var_is_login($var) {
    	$is_login = (strlen($var) >= 5 && strlen($var) <= 20);
    	//$is_login   = (eregi("^[-_[:alnum:]]{3,16}$",$var));
    	return ($is_login) ? $var : FALSE;
    }
    
    /**
     * Add parameters to url.
     *
     * @param string $varName Variable name to add.
     * @param unknown_type $varVal Variable value
     * @param unknown_type $uri Url to which 
     * @return unknown
    */
    public static function urlAddToQuery($varName, $varVal, $uri=null) {
    	$result = '';
    	$beginning = '';
    	$ending = '';
    
    	if (is_null($uri)) {//Piece together uri string
    		$beginning = $_SERVER['PHP_SELF'];
    		$ending = ( isset($_SERVER['QUERY_STRING']) ) ? $_SERVER['QUERY_STRING'] : '';
    	} else {
    		$qstart = strpos($uri, '?');
    		if ($qstart === false) {
    			$beginning = $uri; //$ending is '' anyway
    		} else {
    			$beginning = substr($uri, 0, $qstart);
    			$ending = substr($uri, $qstart);
    		}
    	}
    
    	if (strlen($ending) > 0) {
    		$vals = array();
    		$ending = str_replace('?','', $ending);
    		parse_str($ending, $vals);
    		$vals[$varName] = $varVal;
    		$ending = '';
    		$count = 0;
    		foreach($vals as $k => $v) {
    			if ($count > 0) { $ending .= '&'; }
    			else { $count++; }
    			$ending .= "$k=" . urlencode($v);
    		}
    	} else {
    		$ending = $varName . '=' . urlencode($varVal);
    	}
    
    	$result = $beginning . '?' . $ending;
    
    	return $result;
    }
    
    /**
     * Create hex string.
     *
     * @param string $s string to encode
     * @return string Returns encoded string
    */
    public static function HexCode($s) {
    	$tmpstr = "";
    	for($i=0; $i<strlen($s); $i++)
    	$tmpstr .= sprintf("%02x", ord($s[$i]));
    	return $tmpstr;
    }
    /**
     * Decode hex string.
     *
     * @param string $s Hex string to decode
     * @return string Returns decoded string
    */
    
    public static function HexDecode($s) {
    	$tmpstr = "";
    	for($i=0; $i<strlen($s); $i+=2) {
    		$j = intval($s[$i].$s[$i+1], 16);
    		$tmpstr .= chr($j);
    	}
    	return $tmpstr;
    }
    
    /**
     * Creates a random string of $pw_length characters suitable for temporary passwords.
     *
     * @param int $pw_length Length of password string to generate
     * @return string Random password string
    */
    public static function generate_password($pw_length = 8) {
    	$password = "";
    
    	// set ASCII range for random character generation
    	$lower_ascii_bound = 50;          // "2"
    	$upper_ascii_bound = 122;       // "z"
    	$i = 0;
    
    	// Exclude special characters and some confusing alphanumerics
    	// o,O,0,I,1,l etc
    	$notuse = array (58,59,60,61,62,63,64,73,79,91,92,93,94,95,96,108,111);
    
    	while ($i < $pw_length) {
    		// random limits within ASCII table
    		$randnum = mt_rand ($lower_ascii_bound, $upper_ascii_bound);
    		if (!in_array ($randnum, $notuse)) {
    			$password .= chr($randnum);
    			$i++;
    		}
    	}
    	return $password;
    }
    
    /**
     * Prepare password to store in database. Perform md5 crypting.
     *
     * @param string $_pass Clear password string
     * @return string Encrypted password
    */
    public static function create_password($login, $_pass)
    {
    	return md5($login . $_pass);
    }
    
    
    /**
     * Interface function for caller systems. Performs an redirect to given url.
     *
     * @param unknown_type $url Url to redirect to 
     * @param unknown_type $msg Message to pass to redirected page
     * @param unknown_type $_from Url to return after redirect
    */
    public static function authRedirect($url,$msg="", $_from = "") 
    {
		global $from;
	
		if(empty($_from))
		{
			$_from = $from;
		}
	
		if(!empty($msg))
			$url = urlAddToQuery("_msg", $msg, $url);
		if(!empty($_from))
			$url = urlAddToQuery("from", $_from, $url);
		header("Location: $url");
		
		exit;
	}

    
    /**
     * Interface function for caller systems. Perform logout.
     *
     * @param unknown_type $domain Absolete parameter. Kept for backward capability.
    */
    public static function Logoff()
    {
    	global $_auth_user;
    
    	if(isset($_auth_user))
    	{
    		$_auth_user->logout();
    	}
    }
    /**
     * Interface function for Webcenter admin. Redirects to Auth Login Page.
     *
     * @param unknown_type $errmsg Message to pass to redirected page.
    */
    public static function goToLoginForm($errmsg=''){
    	global $from;
    	authRedirect(LOGIN_PAGE."?from=$from",$errmsg);
    }
    
    /**
     * Interface function for caller systems. Checks if current loged in user has permissions to access 
     * to some part of administration platform.
     *
     * @param string $realmCode Realm code or part of admin platform to access.
     * @param string_type $permsName Permision level.
     * @return bool	Returns true if current user has access with given access level.
    */
    public static function authCheck($realmCode, $permision) {
    	global $_auth_user;
    
    	if(!isset($_auth_user) || !$_auth_user->isLoggedIn())
    		return false;
    
    	if($_auth_user->login == 'root')
    		return true;
    	return $_auth_user->hasPermissions($realmCode, $permision);
    }
    
    public static function loginCheck()
    {
    	return authCheck('', '');
    }
    
    /**
     * Returns permision code by name.
     *
     * @param string $a_name Permision name 
     * @return int Permision code
    */
    public static function getAccessLevel($a_name)
    {
    	global $arrPerms;
    
    	return array_search($a_name, $arrPerms);
    }
    
    /**
     * Format url of current page.
     *
     * @return string Url.
    */
    public static function getCurrentURL()
    {
    	global $HTTP_HOST, $REQUEST_URI, $SERVER_PORT, $QUERY_STRING;
    
    	$proto	= ($SERVER_PORT == 443) ? "https" : "http";
    
    	return urlencode($proto . "://" . $HTTP_HOST . $REQUEST_URI . '?' . $QUERY_STRING);
    }
    
    /**
     * Format uri of current page.
     *
     * @return string Uri.
    */
    public static function getCurrentURI()
    {
    	global $HTTP_HOST, $REQUEST_URI, $SERVER_PORT, $QUERY_STRING;
    
    	$proto	= ($SERVER_PORT == 443) ? "https" : "http";
    
    	return urlencode($REQUEST_URI . '?' . $QUERY_STRING);
    }
    
    public static function objectToSmarty(&$smarty, &$obj)
    {
    	$vars = get_object_vars($obj);
    	arrayToSmarty($smarty, $vars);
    }
    public static function arrayToSmarty($smarty, $vars)
    {
    	foreach ($vars as $key => $value) {
    		$smarty->assign($key, $value);
    	}
    }
    
    /**
     * Returns true if there is a such registered user
     *
     * @param string $userName User name
     */
    public static function checkUserName($userName)
    {
    	$q = db_query("select * from administrator where login='{$userName}'");
    	
    	if(db_fetch_array($q))
    	{
    		return true;	
    	}
    	
    	return false;
    } 
    
    public static function email_exists($email)
    {
    	$q = db_query("select * from inc_users where email='{$email}'");
    	if(db_fetch_array($q))
    	{
    		return true;	
    	}
    	
    	return false;
    }
    
    public static function get_countries($countries_id = '', $with_iso_codes = false) {
        $countries_array = array();
        if (is_null($countries_id)) {
          if ($with_iso_codes == true) {
            $countries = db_query("select countries_name, countries_iso_code_2, countries_iso_code_3 from countries where countries_id = '" . (int)$countries_id . "' order by countries_name");
            $countries_values = tep_db_fetch_array($countries);
            $countries_array = array('countries_name' => $countries_values['countries_name'],
                                     'countries_iso_code_2' => $countries_values['countries_iso_code_2'],
                                     'countries_iso_code_3' => $countries_values['countries_iso_code_3']);
          } else {
            $countries = db_query("select countries_name from countries where countries_id = '" . (int)$countries_id . "'");
            $countries_values = db_fetch_array($countries);
            $countries_array = array('countries_name' => $countries_values['countries_name']);
          }
        } else {
          $countries = db_query("select countries_id, countries_name from countries order by countries_name");
          while ($countries_values = db_fetch_array($countries)) {
            $countries_array[] = array('countries_id' => $countries_values['countries_id'],
                                       'countries_name' => $countries_values['countries_name']);
          }
        }
    
        return $countries_array;
      }
    
    // Parse the data used in the html tags to ensure the tags will not break
    public static function output_string($string, $translate = false, $protected = false) {
        if ($protected == true) {
          return htmlspecialchars($string);
        } else {
          if ($translate == false) {
            return parse_input_field_data($string, array('"' => '&quot;'));
          } else {
            return parse_input_field_data($string, $translate);
          }
        }
      }
    public static function parse_input_field_data($data, $parse) {
        return strtr(trim($data), $parse);
      }
    
    public static function get_country_name($country_id) 
      {
        $country_array = get_countries($country_id);
    
        return $country_array['countries_name'];
      }
     public static function createQueryString($array, $exclude = array())
     {
     	$str = '';
     	
     	foreach ($array as $name=>$value) 
     	{
     		if(in_array($name, $exclude))
     			continue;
     		if(!empty($str))
     			$str .= "&$name=$value";
     		else 
     			$str .= "$name=$value";
     	}
     	return $str;
     }

    public static function get_gender_text($g)
      {
      	switch($g)
      	{
      		case 'M':
      			return 'Male';
      		case 'F':
      			return 'Female';
      	}
      	return null;
      }
      
    public static function get_param($name, $default=null)
    {
    	if (isset($_GET[$name]))
    	{
    	    return $_GET[$name];
    	}
    	elseif (isset($_POST[$name]))
    	{
    		return $_POST[$name];
    	}
    	return $default;
    }
    
    public static function loadLib($libName)
	{
		require_once CLASSES_DIR. $libName . '.classes.php';
	}

      
}









if (!function_exists('array_diff_keys'))
{

	/**
     * array_diff_keys for PHP version < 5.0
     *
     * @return array
	*/
	function array_diff_keys()
	{
		$args = func_get_args();

		$res = $args[0];
		if(!is_array($res)) {
			return array();
		}

		for($i=1;$i<count($args);$i++) {
			if(!is_array($args[$i])) {
				continue;
			}
			foreach ($args[$i] as $key => $data) {
				unset($res[$key]);
			}
		}
		return $res;
	}
}
?>